<template>
  <div class="menu">
    <el-tabs v-model="activeName">
      <el-tab-pane name="first">
        <span slot="label"><i class="el-icon-user-solid"></i>玩家</span>
        <Player key="p0" :player="player0" :ready="ready0" @upload-avatar="onUpload"/>
        <el-divider/>
        <Player key="p1" :player="player1" :ready="ready1" @upload-avatar="onUpload"/>
      </el-tab-pane>
      <el-tab-pane name="second" class="center-wrap">
        <span slot="label"><i class="el-icon-menu"></i>菜单</span>
        <h2 v-if="$cookies.isKey('room')">
          <i class="el-icon-office-building"></i>房间号{{$cookies.get('room').roomId}}
        </h2>
        <h2 v-else>
          <i class="el-icon-error"></i>未加入
        </h2>
        <el-tag effect="plain" type="success">{{ `第 ${round} 回合` }}</el-tag>
        <div class="prog">
          <el-progress :text-inside="true" :stroke-width="26" :percentage="timePercent" color="#409EFF"/>
        </div>
        <div class="order">
          <Chess
            :disAble="true"
            :isBlank="false"
            :chessObj="myOrder ? {name: '帥', side: 0} : {name: '将', side: 1}"
          />
        </div>
        <div v-for="item in featureBtn" :class="item.category" :key="item.text">
          <el-divider v-if="item.category === 'divider'"/>
          <el-button
            v-else
            :type="item.type"
            @click="item.click()"
            :disabled="item.disabled()"
            plain
          >
            {{ item.text }}
          </el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane name="third">
        <span slot="label"><i class="el-icon-s-order"></i>记录</span>
        <div v-for="(item, index) in this.history" :key="`${index}~${item}`" class="item">{{ item }}</div>
      </el-tab-pane>
      <el-tab-pane name="forth">
        <span slot="label"><i class="el-icon-chat-dot-round"></i>聊天</span>
        <div v-for="item in this.chat" :key="item.msg" class="item">
          <p class="color-blue">{{ item.name + ':' }}</p>
          {{ item.msg }}
        </div>
        <div style="margin: 1em;">
          <el-input placeholder="请输入内容" v-model="textInput" clearable/>
        </div>
        <el-button type="primary" @click="send" plain>发送消息</el-button>
        <el-button type="primary" @click="clear" plain>清除所有</el-button>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import Player from '@/components/Player.vue';
import Chess from '@/components/Chess.vue';
import {getUserInfo, uploadAvatar} from '@/api/index.js';
export default {
  name: 'Menus',
  props: {
    timePercent: {
      type: Number,
      default: 100
    }
  },
  components: {
    Player,
    Chess
  },
  created() {
    this.getPlayers();
  },
  data() {
    return {
      player0: {},
      player1: {},
      ready0: false,
      ready1: false,
      activeName: 'second',
      textInput: '',
      myOrder: 1, // 不指代行棋顺序
      roomId: this.$cookies.isKey('room') ? this.$cookies.get('room').roomId : -1,
      round: 0,
      history: [],
      chat: [],
      drawTimes: 3, // 游戏重新开始时应该重置
      repentTimes: 4, // 游戏重新开始时应该重置
      refreshDis: false,
      featureBtn: [
        {category: 'divider'},
        {category: 'btn', type: 'primary', click: this.checkEdition, text: '准备游戏', disabled: () => false},
        {category: 'btn', type: 'primary', click: this.leave, text: '离开房间', disabled: () => false},
        {category: 'btn', type: 'primary', click: this.refresh, text: '刷新棋盘', disabled: () => this.refreshDis},
        {category: 'divider'},
        {category: 'btn', type: 'info', click: this.offerDraw, text: '求和', disabled: () => this.drawTimes <= 0},
        {category: 'btn', type: 'info', click: this.admitDefeat, text: '认输', disabled: () => false},
        {category: 'btn', type: 'info', click: this.repentance, text: '悔棋', disabled: () => false}
      ]
    };
  },
  methods: {
    offerDraw() { // 求和
      if (this.drawTimes > 0) {
        this.drawTimes--;
        this.$notify({title: '提示', message: '剩余求和次数:' + this.drawTimes});
        const {roomId, side} = this.$cookies.get('room');
        this.$socket.emit('draw', {offer: true, roomId, side});
      }
    },
    admitDefeat() { // 认输
      this.$confirm('确定认输?', '提示', {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'}).then(() => {
        const {roomId, side} = this.$cookies.get('room');
        this.$socket.emit('defeat', {roomId, side});
      }).catch(() => {
        this.$message({type: 'info', message: '已取消'});
      });
    },
    repentance() { // 悔棋
      if (this.drawTimes > 0) {
        this.repentTimes--;
        this.$notify({title: '提示', message: '剩余悔棋次数:' + this.drawTimes});
        const {roomId, side} = this.$cookies.get('room');
        this.$socket.emit('repentance', {offer: true, roomId, side});
      }
    },
    refresh() { // 刷新棋盘
      this.refreshDis = true;
      this.$socket.emit('recovery', {roomId: this.$cookies.get('room').roomId});
      setTimeout(() => {
        this.refreshDis = false;
      }, 5000);
    },
    addHistory(data) {
      const temp = {
        'start': [data.start[0] + 1, data.start[1] + 1],
        'finish': [data.finish[0] + 1, data.finish[1] + 1]
      };
      if (this.history.length >= 20) {
        this.history = []; // 防止推算隐形棋子历史
      }
      this.history.push(`${data.side === 0 ? '红方' : '黑方'}${data.name}:从(${temp.start})到(${temp.finish})`);
    },
    leave() {
      if (!this.$cookies.isKey('room')) {
        this.$router.push({name: 'hall'});
        return false;
      }
      this.$socket.emit('leave', {roomId: this.$cookies.get('room').roomId});
      this.$cookies.remove('room');
      this.$cookies.set('user', {...this.$cookies.get('user'), ready: false});
      this.$router.push({name: 'hall'});
    },
    send() {
      this.$socket.emit('chat', {msg: this.textInput});
      this.textInput = '';
    },
    clear() {
      this.chat = [];
    },
    nextPlayer() {
      this.myOrder = 1 - this.myOrder;
      if (this.myOrder) {
        this.round++;
      }
    },
    backPlayer() {
      this.myOrder = 1 - this.myOrder;
      if (!this.myOrder) {
        this.round--;
      }
    },
    checkEdition() {
      if (this.$cookies.get('room').edition === 0) {
        this.$emit('giveSkill');
      }
      else {
        this.ready();
      }
    },
    ready(skill) {
      const room = this.$cookies.get('room');
      this.roomId = room.roomId;
      this.$socket.emit('prepare', {sk: skill, roomId: this.roomId, side: room.side});
      this[`ready${room.side}`] = true;
      if (room.robot) {
        this.$socket.emit('start', {roomId: this.roomId}); // AI自动开始
      }
      if (this.ready0 && this.ready1) {
        this.$socket.emit('start', {roomId: this.roomId});
      }
      this.$cookies.set('user', {...this.$cookies.get('user'), ready: true});
    },
    cancel() { // 取消准备
      const s = this.$cookies.get('room').side;
      this[`ready${s}`] = false;
      this.$cookies.set('user', {...this.$cookies.get('user'), ready: false});
    },
    getPlayers() {
      getUserInfo({id: this.$cookies.get('room').roomId}).then(res => {
        // 这里有一个BUG，准备状态没有获取到
        this.player0 = res.data.a || {};
        this.player1 = res.data.b || {};
      }).catch(() => {
        this.$message({message: '很遗憾 加载玩家信息失败', type: 'warning'});
      });
    },
    onUpload(value) {
      uploadAvatar({
        uid: this.$cookies.get('user').id,
        url: value
      }).then(res => {
        if (res.data.succeed) {
          this.getPlayers();
          this.$message({type: 'success', message: '上传成功'});
        }
        else {
          this.$message.error('上传失败');
        }
      }).catch(() => {
        this.$message({type: 'info', message: '上传失败'});
      });
    }
  },
  sockets: {
    chat(data) {
      this.chat.push({name: data.name, msg: data.textInput});
    },
    enter(data) {
      this.getPlayers();
    },
    prepare(data) {
      this[`ready${data.side}`] = true;
      if (this.ready0 && this.ready1) {
        this.$socket.emit('start', {roomId: this.roomId});
      }
    }
  }
};
</script>

<style scoped>
.menu {
  width: 290px;
  position: absolute;
  top: 10px;
  text-align: center;
}
.top {
  top: 0px;
}
.bottom {
  bottom: 0px;
}
.btn {
  width: 100%;
  display: block;
  text-align: center;
  margin-top: 1em;
}
.divider {
  width: 100%;
}
.el-divider--horizontal {
  width: 80%;
  margin-left: 10%;
}
.item {
  text-align: left;
  margin-bottom: 1em;
  margin-left: 1em;
}
.order {
  margin-top: 1em;
}
.prog {
  margin: 1em 0;
  width: 80%;
}
.center-wrap {
  flex-direction: column;
  align-items: center;
  display: flex;
}
</style>
